package com.xc.stock.utils;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;

import com.google.common.collect.Lists;

public class Beans {
	public static <T, U> U mapper(final T source, final Class<U> destType) {
		if(source == null) return null;
		return Dozers.mapper.map(source, destType);
	}
	
	public static <T, U> List<U> mappers(final List<T> sources, final Class<U> destType) {
		final List<U> dest = Lists.newArrayList();
		for (T source : sources) {
			dest.add(Dozers.mapper.map(source, destType));
		}

		return dest;
	}
	public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
		BeanUtils.copyProperties(source, target, ignoreProperties);
	}

	public static void copyProperties(Object source, Object target) {
		BeanUtils.copyProperties(source, target);
	}
	
	/**
	 * 将属性从source->target复制, 忽略target的null的值的属性
	 * 
	 */
	public static void copyPropertiesIgnoreNull(Object source, Object target) {
		BeanUtils.copyProperties(source, target, getNullProperties(source));
	}
	
	public static void copyPropertiesIgnoreNull(Object source, Object target, String... ignoreProperties) {
		String[] nullProperties = getNullProperties(source);
		List<String> list = Lists.newArrayList(nullProperties);
		for(String p : ignoreProperties) {
			if(! list.contains(p)) {
				list.add(p);
			}
		}
		
		String[] all = new String[list.size()];
		BeanUtils.copyProperties(source, target, list.toArray(all));
	}

	/**
	 * 查询 src 属性值为<code>null</code> 的字段集
	 */
	private static String[] getNullProperties(Object src) {
		BeanWrapper srcBean = new BeanWrapperImpl(src);
		PropertyDescriptor[] pds = srcBean.getPropertyDescriptors();
		Set<String> emptyName = new HashSet<>();
		for (PropertyDescriptor p : pds) {
			Object srcValue = srcBean.getPropertyValue(p.getName());
			if (srcValue == null) {
				emptyName.add(p.getName());
			}
		}
		String[] result = new String[emptyName.size()];
		return emptyName.toArray(result);
	}

}
